
import UIKit
import WebKit
class MYGTopicContentTableViewCell: UITableViewCell {
    var isIndInfo:Bool = false{
        didSet{
            previewLabel.isHidden = isIndInfo
            previewImageV.isHidden = isIndInfo
        }
    }
    var getWebViewHeightCallback:((Double)->Void)?
    var model = MYGTopicDetailModel()
    var newsModel = MYGInformationModel()
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(SCALEWIDTH(24))
            make.top.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-SCALEWIDTH(24))
        }
        
        contentView.addSubview(headerImageBV)
        headerImageBV.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(SCALEWIDTH(24))
            make.top.equalTo(titleLabel.snp.bottom).offset(SCALEWIDTH(20))
            make.size.equalTo(CGSize(width: SCALEWIDTH(32), height: SCALEWIDTH(32)))
        }
        
        contentView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(headerImageBV.snp.right).offset(SCALEWIDTH(8))
            make.top.equalTo(headerImageBV.snp.top)
            make.height.equalTo(SCALEWIDTH(18.5))
        }
        
        contentView.addSubview(departmentLabel)
        departmentLabel.snp.makeConstraints { make in
            make.left.equalTo(nameLabel.snp.right).offset(SCALEWIDTH(8))
            make.centerY.equalTo(nameLabel)
            make.height.equalTo(SCALEWIDTH(16.5))
        }
        
        contentView.addSubview(previewLabel)
        previewLabel.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-SCALEWIDTH(27))
            make.centerY.equalTo(headerImageBV)
            make.height.equalTo(SCALEWIDTH(18.5))
        }
        contentView.addSubview(previewImageV)
        previewImageV.snp.makeConstraints { make in
            make.right.equalTo(previewLabel.snp.left).offset(-SCALEWIDTH(4))
            make.centerY.equalTo(headerImageBV)
            make.width.equalTo(SCALEWIDTH(18.5))
            make.height.equalTo(SCALEWIDTH(13))
        }
        
        contentView.addSubview(hospitallabel)
        hospitallabel.snp.makeConstraints { make in
            make.left.equalTo(headerImageBV.snp.right).offset(SCALEWIDTH(8))
            make.right.equalToSuperview().offset(-15)
            make.top.equalTo(departmentLabel.snp.bottom)
        }
        
        contentView.addSubview(contentWebView)
        contentWebView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(SCALEWIDTH(24))
            make.right.equalToSuperview().offset(-SCALEWIDTH(24))
            make.height.equalTo(0)
            make.top.equalTo(hospitallabel.snp.bottom).offset(SCALEWIDTH(20))
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private lazy var titleLabel: UILabel = {
        let cont = UILabel()
        cont.text = "几种二尖瓣返流的治疗方法"
        cont.font = .medium(22)
        cont.textColor = .rgba(51, 51, 51)
        cont.numberOfLines = 0
        return cont
    }()
    private lazy var headerImageBV: UIImageView = {
        let cont = UIImageView()
        cont.layer.cornerRadius = SCALEWIDTH(16)
        cont.layer.masksToBounds = true
        cont.contentMode = .scaleAspectFill
        return cont
    }()
    private lazy var nameLabel: UILabel = {
        let cont = UILabel()
        cont.text = "乔淑琴"
        cont.font = .medium(13)
        cont.textColor = .rgba(51, 51, 51)
        return cont
    }()
    private lazy var departmentLabel: UILabel = {
        let cont = UILabel()
        cont.text = "副主任医师"
        cont.font = .regular(12)
        cont.textColor = .rgba(128, 128, 128)
        return cont
    }()
    private lazy var hospitallabel: UILabel = {
        let cont = UILabel()
        cont.text = "北京安贞医院  2022-07-25 16:44"
        cont.font = .regular(12)
        cont.numberOfLines = 0
        cont.textColor = .rgba(128, 128, 128)
        return cont
    }()
     lazy var contentWebView: WKWebView = {
        let cont = WKWebView()
        cont.navigationDelegate = self
//         cont.isOpaque = false
         if #available(iOS 11.0, *) {
             cont.scrollView.contentInsetAdjustmentBehavior = .never
             }
         cont.scrollView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)

        return cont
    }()
    
    deinit {
        contentWebView.scrollView.removeObserver(self, forKeyPath: "contentSize")
    }
    lazy var previewImageV: UIImageView = {
        let cont = UIImageView()
        cont.image = UIImage(named: "MYG_home_preview")
        cont.isHidden = true
        return cont
    }()
    lazy var previewLabel: UILabel = {
        let cont = UILabel()
        cont.text = "2529"
        cont.font = .regular(12)
        cont.textColor = .rgba(153, 153, 153)
        cont.isHidden = true
        return cont
    }()
    
    func bindData(_ data: MYGTopicDetailModel) {
        if self.model.id == data.id {return}
        self.model = data
        self.titleLabel.text = data.title
        self.headerImageBV.sd_setImage(with: URL(string: data.doctor.avatar), placeholderImage: UIImage.init(named: "MYG_defaultAvatar_doctor"), context: nil)
        self.nameLabel.text = data.doctor.name
        self.departmentLabel.text = data.doctor.title
        self.hospitallabel.text = data.doctor.hospital + "  " + data.updated_at.toTimeString()
        self.contentWebView.loadHTMLString(data.content, baseURL: nil)
    }
    
    func bindNewsData(_ data: MYGInformationModel) {
        if self.newsModel.id == data.id {return}
        self.newsModel = data
        self.titleLabel.text = data.title
        self.previewLabel.text = "\(data.browse_num)"
        self.headerImageBV.sd_setImage(with: URL(string: data.from_img), placeholderImage: UIImage.init(named: "MYG_defaultAvatar_doctor"), context: nil)
        self.nameLabel.text = data.from
        self.departmentLabel.isHidden = true
        self.hospitallabel.isHidden = true
        self.contentWebView.loadHTMLString(data.content, baseURL: nil)
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
           if keyPath == "contentSize" {
               if isIndInfo {
                   if self.newsModel.isLoad == true {return}
               }else {
                   if self.model.isLoad == true {return}
               }
               
               let height = contentWebView.scrollView.contentSize.height
               self.contentWebView.snp.updateConstraints { make in
                   make.height.equalTo(height)
               }
               if let c = self.getWebViewHeightCallback {
                   c(height + self.contentWebView.frame.origin.y)
               }
           }
       }
}
extension MYGTopicContentTableViewCell:WKNavigationDelegate {
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '230%'", completionHandler: nil)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
            if self.isIndInfo {
                self.newsModel.isLoad = true
            }else {
                self.model.isLoad = true

            }
        })
       

//        webView.evaluateJavaScript("Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight)") { (result, error) in
//
//            if let height = result as? Double {
//                let ff =  (height / 3 + screenWidth * 38.0/75.0) / 2.3
//                self.contentWebView.snp.updateConstraints { make in
//                    make.height.equalTo(ff)
//                }
//                if let c = self.getWebViewHeightCallback {
//                    c(ff + self.contentWebView.frame.origin.y)
//                }
//            }
//        }
//        webView.evaluateJavaScript("document.readyState", completionHandler: { (_, error) in
//            if error == nil {
//                webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { (result, error) in
//                    if let height = result as? Double {
////                        self.contentWebView.snp.updateConstraints { make in
////                            make.height.equalTo(height)
////                        }
//                        if let c = self.getWebViewHeightCallback {
//                            c(height)
//                        }
//                    }
//                })
//            }
//        })

        }
    
    
}
